package com.blogspot.wanyancan.server;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 3383558291702254055L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String rootDirectory = "/home/billy/uploadffTemp/";
		boolean writeToFile = true;
		String returnOKMessage = "OK";

		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		PrintWriter out = response.getWriter();

		// Create a factory for disk-based file items

		if (isMultipart) {
			// We are uploading a file (deletes are performed by on multipart
			// requests)
			FileItemFactory factory = new DiskFileItemFactory();

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			// Parse the request
			try {
				List items = upload.parseRequest(request);
				// Process the uploaded items
				Iterator iter = items.iterator();
				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();

					if (item.isFormField()) {
					} else {
						if (writeToFile) {
							String fileName = item.getName();
							if (fileName != null && !fileName.equals("")) {
								fileName = FilenameUtils.getName(fileName);
								File uploadedFile = new File(rootDirectory
										+ fileName);
								try {
									item.write(uploadedFile);
									out.print(returnOKMessage);
								} catch (Exception e) {
									e.printStackTrace();
									out.print(e.getLocalizedMessage());
								}
							}
						} else {
						}
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
				out.print(e.getLocalizedMessage());
			}
		} else {
			// Process a request to delete a file
			String[] paramValues = request
					.getParameterValues("uploadFormElement");
			for (int i = 0; i < paramValues.length; i++) {
				String fileName = FilenameUtils.getName(paramValues[i]);
				File deleteFile = new File(rootDirectory + fileName);
				if (deleteFile.delete()) {
					out.print(returnOKMessage);
				}
			}
		}
	}
}